<template>
    <a-layout id="components-layout-demo-side" style="min-height: 100vh">
        <a-layout-sider  style="-webkit-box-shadow:2px 0 6px rgba(0,21,41,0.35);box-shadow:2px 0 6px rgba(0,21,41,0.35)"
          v-model="collapsed" collapsible>
            <div class="logo">
                <img src="../assets/m10.png"
                     v-show="collapsed === true" style="width: auto;height: auto;max-width: 100%;max-height: 100%"
                     alt="">
                <img v-show="collapsed === false" style="width: auto;height: auto;max-width: 100%;max-height: 100%"
                     src="../assets/lte.png" alt="">
                <!--        <p style="text-align: center;color: white">LTE</p>-->
            </div>
            <a-menu
                    theme="dark"
                    :default-selected-keys="defaultSelectedMenu"
                    mode="inline">

                <!--    单层菜单 单独刷   -->
                <a-menu-item
                        v-for="mitem in menuSet" v-bind:key="mitem.menuId"
                        v-if="mitem.isMenu===1&& mitem.hasChild===0&& mitem.menuLevel===1"
                        :key="mitem.routerName">
                    <a-icon :type="mitem.iconType"/>
                    <span>{{ mitem.note }}</span>
                    <router-link :to="mitem.routerPath"></router-link>
                </a-menu-item>

                <!-- 双层菜单 单独刷-->
                <a-sub-menu v-for="(levelOne,i) in menuSet" v-bind:key="levelOne.menuId"
                            v-if="levelOne.isMenu===1 && levelOne.hasChild===1 && levelOne.menuLevel===1"
                >
                    <span slot="title"><a-icon v-bind:type="levelOne.iconType"/><span>{{ levelOne.note }}</span></span>

                    <a-menu-item v-if="getSubMenuSet(levelOne).length>0"
                                 v-for="subMenu in getSubMenuSet(levelOne)" v-bind:key="subMenu.routerName">
                        <a-icon v-show="subMenu.iconType !== undefined && subMenu.iconType !== null && subMenu.iconType !== ''"
                                :type="subMenu.iconType"/>
                        <span>{{ subMenu.note }}</span>
                        <router-link :to="subMenu.routerPath"></router-link>
                    </a-menu-item>
                </a-sub-menu>


            </a-menu>
        </a-layout-sider>

        <a-layout>
            <a-layout-header style="background: #fff; padding: 0;-webkit-box-shadow:0 1px 4px rgba(0,21,41,0.08) ; box-shadow:0 1px 4px rgba(0,21,41,0.08)">
                <div style="float: right">
                    <span>{{weatherInfo.city}}天气：{{weatherInfo.wea+weatherInfo.tem2+'~'+weatherInfo.tem1}}度，{{weatherInfo.win+weatherInfo.win_speed}} </span>
                    <TimeOut style="display: inline-block"></TimeOut>
                    <span style="margin-right: 10px">{{weatherInfo.week}}</span>

                    <a-popover style="margin-right: 15px"
                               v-model="visibleMsgBox" @visibleChange="handleHoverChange" title="消息通知" trigger="hover">
                        <template slot="content">
                            <p v-for="(item,i) in this.msgBoxInfos" v-bind:key="i">
                                <span>{{ i + 1 }}.</span>
                                <span v-html="item.content"></span>
                                <a-button @click="delAlreadyReadMsg(item)" type="danger" size="small">标为已读</a-button>
                                <br>
                            </p>
                            <p v-show="msgBoxInfos.length===0">
                                暂无信息
                            </p>


                        </template>
                        <a-badge :count="this.msgBoxInfos.length">
                            <a-button>
                                <a-icon type="message"/>
                                消息盒
                            </a-button>
                        </a-badge>
                    </a-popover>


                    <a-button @click="showPersonal()" style="margin-right: 15px">
                        <a-icon type="user"/>
                        {{ loginAccount }}
                    </a-button>

                    <a-button @click="screenfullBtn()" style="margin-right: 15px">
                        <a-icon type="fullscreen"/>
                        全屏
                    </a-button>

                    <a-button @click="logoutSys()" type="primary" style="margin-right: 15px">
                        <a-icon type="logout"/>
                        退出
                    </a-button>
                </div>
            </a-layout-header>

            <a-layout-content style="margin: 0 16px">
                <a-breadcrumb style="margin: 16px 0">
                    <!--          <a-breadcrumb-item>User</a-breadcrumb-item>-->
                    <a-breadcrumb-item>{{ this.$route.name }}</a-breadcrumb-item>
                    <!--          <a-breadcrumb-item v-for=" item in this.$route.matched" :key="item.path"> {{item.path.substring(1,item.path.length)}}</a-breadcrumb-item>-->

                </a-breadcrumb>
                <div :style="{ padding: '14px', background: '#fff', minHeight: '360px' }">

                    <router-view></router-view>

                </div>
            </a-layout-content>
            <a-layout-footer style="text-align: center">
                Ant Design ©2018 Created by Ant UED
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>
<script>
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    import {getPremByUserId} from "../api/backend-req/login";
    import {logout} from "../api/backend-req/login";
    import TimeOut from "@/components/TimeOut";
    import screenfull from 'screenfull'
    import SockJS from "sockjs-client";
    import Stomp from "stompjs";
    import originJSONP from "jsonp";

    export default {
        name: 'SysLayout',
        components: {
            TimeOut
        },
        data() {
            return {
                myMockData:require("../../mock/menu.json"),
                mySetting:require("../../mock/my-setting.json"),
                weatherInfo: {},
                defaultSelectedMenu: ['defaultHome'],
                menuSet: [], //仅刷菜单组件用
                loginAccount: 'Personal',
                collapsed: false,
                currentUserId: null,
                stompClient: "",
                msgBoxInfos: [],
                visibleMsgBox: false,
                arrys: [],
            };
        },
        created() {
            this.getWeather();
        },
        methods: {
            getWeather() {
                let url3 = 'https://www.tianqiapi.com/api?version=v6&appid=85618448&appsecret=9ZfOvBsd&callback=ckp';
                let opts = {
                    prefix: 'ckp'
                }
                //发起jsonP请求
                originJSONP(url3, opts, (err, data) => {
                    console.log('????????????????===')
                    if (!err) {
                        console.log(data);
                        this.weatherInfo = data;
                    } else {
                        console.log(err)
                    }
                });
            },
            test1(v1) {
                console.log('------')
                console.log(v1);
                console.log(this.defaultSelectedMenu);
                console.log(this.$refs.aMenuRef)
                this.$forceUpdate();


            },

            handleHoverChange(val) {

                console.log('===================');
                console.log(val);
                if (val) {
                    //通知后端推送webSocket
                    console.log('通知后端推送webSocket')
                    let loginInfoStr = sessionStorage.getItem('loginInfo');
                    if (loginInfoStr !== undefined && loginInfoStr !== null) {
                        let currentUserId = JSON.parse(loginInfoStr).userId;
                        let req = '/lte/sendToFront?userId=' + currentUserId;
                        this.$reqGlobal.get(req).then(res => {
                            console.log(res);
                            this.visibleMsgBox = true;
                        });
                    }
                }

            },

            //msgBox表为已读
            async delAlreadyReadMsg(item) {
                this.msgBoxInfos.splice(this.msgBoxInfos.indexOf(item), 1);
                //线程睡眠1秒后关闭msgBox
                await sleep(1000);
                this.visibleMsgBox = false;
            },

            clearSessionAndPushLogin() {
                //前台清掉sessionStorage
                sessionStorage.clear();
                console.log(
                    `%c lte-admin %c 退出系统ok %c`,
                    'background:blue ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
                    'background:red ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
                    'background:transparent'
                );
                this.$router.push({path: '/'});
            },
            //退出按钮事件
            logoutSys() {
                clearInterval(this.timer);
                this.disconnect();

                //后台清掉redis
                logout().then(res => {
                    console.log(res);
                    this.clearSessionAndPushLogin();
                }).catch(err => {
                    console.log(err);
                    this.clearSessionAndPushLogin();
                });

            },


            showPersonal() {
                this.$router.push({path: '/personal'});
            },


            //全屏按钮事件
            screenfullBtn() {
                if (!screenfull.isEnabled) {
                    this.$message.warning('浏览器不支持全屏!');
                    return false;
                }
                screenfull.toggle();
                console.log(screenfull.isFullscreen)
                if (screenfull.isFullscreen) {
                    this.$message.success('页面已退出全屏!');
                } else {
                    this.$message.success('页面已全屏显示!');
                }
            },
            getSubMenuSet(levelOne) {
                let arr = [];
                this.menuSet.forEach(m => {
                    if (m.parentMenuId === levelOne.menuId) {
                        arr.push(m);
                    }
                });
                return arr;
            },

            /**
             * 连接后台ws
             */
            connection() {
                const _this = this;
                // 建立连接对象
                let socket = new SockJS("/ws");
                // 获取STOMP子协议的客户端对象
                this.stompClient = Stomp.over(socket);
                // 定义客户端的认证信息,按需求配置
                // let headers = {
                //   Authorization: ""
                // };
                // 向服务器发起websocket连接
                this.stompClient.connect(
                    {},
                    function (res) {
                        console.log(res)
                        console.log('------subscribe---------------')
                        //连接成功 订阅系统信息主题消息
                        console.log(_this.stompClient)
                        let url = '/topic/welcomInfo/' + _this.currentUserId;
                        _this.stompClient.subscribe(url, function (msg) {
                            console.log(msg);
                            _this.msgBoxInfos = [];
                            _this.msgBoxInfos.unshift(JSON.parse(msg.body));
                            console.log(_this.msgBoxInfos)
                        });

                    },
                    function (error) {
                        // 连接发生错误时的处理函数
                        console.log("失败");
                        console.log(error);
                    }
                );


            },

            initWebSocket() {
                this.connection();
                let that = this;
                // 断开重连机制,尝试发送消息,捕获异常发生时重连
                this.timer = setInterval(() => {
                    try {
                        if (that.stompClient !== undefined || that.stompClient !== "") {
                            that.stompClient.send("/app/test");
                        }
                    } catch (err) {
                        console.log("断线了: " + err);
                        that.connection();
                    }
                }, 10000);


            },

            openNotification() {
                this.$notification.success({
                    message: '消息提醒',
                    placement: 'bottomRight',
                    duration: 2,
                    description:
                        '欢迎进入 LteAdmin',
                    onClick: () => {
                        console.log('Notification Clicked!');
                    },
                });
            },

            /**
             * 断开连接
             *
             */
            disconnect() {
                if (this.stompClient) {
                    this.stompClient.disconnect();
                }
            },

        },
        mounted() {
            let loginInfoStr = sessionStorage.getItem('loginInfo');
            if (loginInfoStr !== undefined && loginInfoStr !== null) {
                this.loginAccount = JSON.parse(loginInfoStr).userName;
                this.currentUserId = JSON.parse(loginInfoStr).userId;
                this.initWebSocket();

                let req = {
                    userId: JSON.parse(loginInfoStr).userId
                };
                getPremByUserId(req).then(res => {
                    if (res.data.code === 0) {

                        console.warn(this.myMockData);
                        console.warn(this.mySetting);
                        if (this.mySetting.dev === true){
                            console.warn('启用了开发模式的菜单数据!')
                            res.data = this.myMockData;
                        }
                        sessionStorage.setItem('permData', JSON.stringify(res.data.data));

                        let resArr = [];
                        let oringArr = [];
                        oringArr = res.data.data.menuEntitySet;
                        oringArr.forEach(a => {
                            if (a.isMenu === 1) {
                                resArr.push(a);
                            }
                        });
                        this.menuSet = resArr;
                        //欢迎进入系统
                        this.openNotification();
                    } else {
                        sessionStorage.clear();
                        this.$router.push({path: '/'});
                        this.$message.success('用户未配置菜单权限!');
                    }
                })
            } else {
                this.loginAccount = 'Personal';
            }


        },
        watch: {},
        beforeDestroy() {
            clearInterval(this.timer);
            this.disconnect();

        }
    };
</script>

<style>
    #components-layout-demo-side .logo {
        height: 38px;
        background: rgba(255, 255, 255, 0.2);
        margin: 16px;
        line-height: 38px;
    }
</style>
